# -*- encoding: utf-8 -*-
import win32api
import win32gui
import win32con
import win32process
import win32event
import time

from pystray import MenuItem as item
import pystray
from PIL import Image
import tkinter as tk
from threading import Timer
from sys import exit

mutex = win32event.CreateMutex(None, False, 'python.Running')
if win32api.GetLastError() > 0:
    print('程序已运行...')
    exit(0)


def update():
    global CFG
    try:
        CFG["boundaryTime"] = int(eBoundaryTime.get())
        CFG["loopTime"] = int(eLoopTime.get())
        setCfg(CFG)
    except BaseException as e:
        print(e)


def getCfg():
    res = {
        "boundaryTime": 180,
        "loopTime": 5,
    }
    try:
        with open("config.data") as f:
            res = eval(f.read())
    except BaseException as e:
        setCfg(res)
    return res


def setCfg(t):
    try:
        with open("config.data", "w", encoding="utf8") as f:
            f.write(str(t))
    except BaseException as e:
        print(e)


CFG = getCfg()
# loopTime =
window = tk.Tk()
window.title("应用活动状态管理")
window.geometry("320x480")

lBoundaryTime = tk.Label(window, text="闲置时长(秒)")
lBoundaryTime.pack(pady=(120, 0))

varBoundaryTime = tk.StringVar()
varBoundaryTime.set(CFG["boundaryTime"])
eBoundaryTime = tk.Entry(window, textvariable=varBoundaryTime)
eBoundaryTime.pack(pady=(4, 0))

lLoopTime = tk.Label(window, text="轮询周期(次/秒)")
lLoopTime.pack(pady=(4, 0))

varLoopTime = tk.StringVar()
varLoopTime.set(CFG["loopTime"])
eLoopTime = tk.Entry(window, textvariable=varLoopTime)
eLoopTime.pack(pady=(4, 0))


b = tk.Button(window, text="更新配置",
              width=15, height=1, command=update)
b.pack(pady=(10, 0))

last_input = int(win32api.GetLastInputInfo() / 1000)
last_change = int(time.time())


def killMstsc():
    hWndList = []
    win32gui.EnumWindows(lambda hWnd, param: param.append(hWnd), hWndList)
    for hwnd in hWndList:
        # title = win32gui.GetClassName(hwnd)
        text = win32gui.GetWindowText(hwnd)
        if "远程桌面连接" in text:
            try:
                # win32gui.SetForegroundWindow(hwnd)  # 使当前窗口在最前
                # win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
                # # 根据窗口句柄获取 进程ID 下面的 方法二
                _id = win32process.GetWindowThreadProcessId(hwnd)

                # 根据ID打开进程
                handle = win32api.OpenProcess(1, False, _id[1])
                # 根据进程句柄关闭进程
                win32api.TerminateProcess(handle, -1)
            except BaseException as e:
                print(e)


def monitor():
    global last_input, last_change, boundaryTime
    now_input = int(win32api.GetLastInputInfo() / 1000)
    if now_input != last_input:
        last_input = now_input
        last_change = int(time.time())
    dot = int(time.time()) - last_change
    print("dot:", dot)
    if dot > CFG["boundaryTime"]:
        print("killing...")
        killMstsc()
    timer = Timer(CFG["loopTime"], monitor)
    timer.start()


def quit_window(icon, item):
    icon.stop()
    window.destroy()


def show_window(icon, item):
    icon.stop()
    window.after(0, window.deiconify)


def withdraw_window():
    window.withdraw()
    image = Image.open("image.ico")
    menu = (item('退出', quit_window), item('显示控制台', show_window))
    icon = pystray.Icon("name", image, "title", menu)
    icon.run()


timer = Timer(CFG["loopTime"], monitor)
timer.start()
window.protocol('WM_DELETE_WINDOW', withdraw_window)
window.mainloop()
